<template>
  <div class="points-earn-history">

    <div class="history-content">
      <div class="filter-section">
        <div class="filter-tabs">
          <div
            class="filter-tab"
            :class="{ active: currentFilter === 'all' }"
            @click="changeFilter('all')"
          >
            全部
          </div>
          <div
            class="filter-tab"
            :class="{ active: currentFilter === 'course' }"
            @click="changeFilter('course')"
          >
            课程学习
          </div>
          <div
            class="filter-tab"
            :class="{ active: currentFilter === 'other' }"
            @click="changeFilter('other')"
          >
            其他
          </div>
        </div>
      </div>

      <div class="history-list">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-list
            v-model="loading"
            :finished="finished"
            :immediate-check="false"
            offset="30"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <div
              class="history-item"
              v-for="record in filteredRecords"
              :key="record.id"
              @click="showRecordDetail(record)"
            >
              <div class="record-info">
                <div class="record-title">{{ record.changeTypeText }}</div>
                <div class="record-details">
                  <div class="record-time">{{ record.time }}</div>
                  <div class="record-extra">
                    <span class="change-type">{{ record.title }}</span>
                    <span class="student-name" v-if="record.studentName">{{ record.studentName }}</span>
                  </div>
                </div>
              </div>
              <div class="record-points" :class="[record.type, { positive: record.points > 0, negative: record.points < 0 }]">
                {{ record.points > 0 ? '+' : '' }}{{ record.points }}
              </div>
            </div>
          </van-list>
          <div class="empty-state" v-if="filteredRecords.length === 0 && !loading && finished">
            <div class="empty-icon">📊</div>
            <div class="empty-text">暂无积分获取记录</div>
          </div>
        </van-pull-refresh>
      </div>
    </div>
  </div>
</template>

<script>
import { getStudentPoints } from '@/api'
import { Icon, PullRefresh, List, Toast, Dialog } from 'vant'

export default {
  name: 'PointsEarnHistory',
  components: {
    [Icon.name]: Icon,
    [PullRefresh.name]: PullRefresh,
    [List.name]: List
  },
  data() {
    return {
      currentFilter: 'all',
      currentStudent: null,
      // 各筛选条件的数据
      filterData: {
        all: { records: [], page: 1, hasMore: true, loading: false, finished: false },
        course: { records: [], page: 1, hasMore: true, loading: false, finished: false },
        other: { records: [], page: 1, hasMore: true, loading: false, finished: false }
      },
      refreshing: false,
      isRefreshing: false // 新增标志位，防止下拉刷新和加载更多同时触发
    }
  },
  created() {
    // 获取路由参数中的学生信息
    this.currentStudent = this.$route.params.studentInfo || null
    // 同时从 localStorage 获取学生信息作为备份
    const storedStudent = localStorage.getItem('currentStudentInfo')
    if (storedStudent) {
      try {
        this.currentStudent = JSON.parse(storedStudent)
      } catch (e) {
        console.error('解析存储的学生信息失败:', e)
      }
    }
    // 初始化加载数据
    this.loadPointsHistory()
  },
  beforeRouteLeave(to, from, next) {
    // 如果返回到积分商城页面，设置标记
    if (to.name === 'pointsMall') {
      sessionStorage.setItem('fromPointsEarnHistory', 'true')
      console.log('设置从积分记录页面返回标记')
    }
    next()
  },
  computed: {
    currentFilterData() {
      return this.filterData[this.currentFilter]
    },
    filteredRecords() {
      return this.currentFilterData.records
    },
    loading: {
      get() {
        return this.currentFilterData.loading
      },
      set(value) {
        this.currentFilterData.loading = value
      }
    },
    finished: {
      get() {
        return this.currentFilterData.finished
      },
      set(value) {
        this.currentFilterData.finished = value
      }
    }
  },
  methods: {
    goBack() {
      this.$router.go(-1)
    },
    changeFilter(filter) {
      this.currentFilter = filter
      // 切换筛选条件时重新加载数据
      const currentFilterData = this.filterData[this.currentFilter]
      if (currentFilterData.records.length === 0) {
        currentFilterData.page = 1
        currentFilterData.hasMore = true
        currentFilterData.loading = false
        currentFilterData.finished = false
        this.loadPointsHistory()
      }
    },
    // 下拉刷新
    onRefresh() {
      if (this.isRefreshing) return // 如果正在刷新，直接返回

      this.isRefreshing = true
      this.refreshing = true
      const currentFilterData = this.filterData[this.currentFilter]
      currentFilterData.page = 1
      currentFilterData.records = []
      currentFilterData.hasMore = true
      currentFilterData.loading = false
      currentFilterData.finished = false
      this.loadPointsHistory()
    },

    // 加载积分记录
    async loadPointsHistory() {
      const currentFilterData = this.filterData[this.currentFilter]

      if (!currentFilterData.hasMore) {
        currentFilterData.loading = false
        currentFilterData.finished = true
        return
      }

      currentFilterData.loading = true

      try {
        // 构建请求参数
        const params = {
          current: currentFilterData.page,
          size: 10
        }

        // 根据筛选条件添加 changeType
        if (this.currentFilter !== 'all') {
          params.changeType = this.getChangeTypeByFilter(this.currentFilter)
        }

        // 添加学生ID
        if (this.currentStudent && this.currentStudent.id) {
          params.studentId = this.currentStudent.id
        }

        const response = await getStudentPoints(params)

        if (response.data.code === 200) {
          const data = response.data.result

          // 处理返回的数据
          if (data.records && data.records.length > 0) {
            const newRecords = data.records.map(item => ({
              id: item.id,
              title: item.reason || '积分变动',
              time: this.formatTime(item.createTime),
              points: item.changePoints || 0,
              type: this.getRecordType(item.changeType),
              changeTypeText: this.getChangeTypeText(item.changeType),
              studentName: item.studentName || ''
            }))

            // 合并数据
            if (currentFilterData.page === 1) {
              currentFilterData.records = newRecords
            } else {
              currentFilterData.records = [...currentFilterData.records, ...newRecords]
            }

            // 判断是否还有更多数据
            currentFilterData.hasMore = data.records.length >= 10
            currentFilterData.finished = !currentFilterData.hasMore

            console.log('当前筛选:', this.currentFilter, '页码:', currentFilterData.page, '是否有更多数据:', currentFilterData.hasMore)
          } else {
            currentFilterData.hasMore = false
            currentFilterData.finished = true
            // 如果是下拉刷新，清空数据
            if (this.refreshing) {
              currentFilterData.records = []
            }
          }
        } else {
          console.error('获取积分记录失败:', response.data.message)
          Toast.fail('获取积分记录失败')
          currentFilterData.hasMore = false
          currentFilterData.finished = true
        }
      } catch (error) {
        console.error('获取积分记录异常:', error)
        Toast.fail('获取积分记录失败')
        currentFilterData.hasMore = false
        currentFilterData.finished = true
      } finally {
        currentFilterData.loading = false

        // 如果是下拉刷新，重置刷新状态
        if (this.refreshing) {
          this.refreshing = false
          this.isRefreshing = false // 重置刷新标志位
        }
      }
    },
    // 根据筛选条件获取 changeType
    getChangeTypeByFilter(filter) {
      const typeMap = {
        'course': 'Course', // 课程学习
        'other': 'Other'    // 其他
      }
      return typeMap[filter] || ''
    },
    // 根据 changeType 获取显示文本（硬编码映射）
    getChangeTypeText(changeType) {
      const typeMap = {
        'Course': '课程学习',
        'Return': '退货返还',
        'Other': '其他',
        'Spending': '积分消费',
        'Issuance': '系统发放',
        'OTHER': '其他'
      }
      return typeMap[changeType] || '其他'
    },
    // 根据 changeType 获取记录类型
    getRecordType(changeType) {
      const typeMap = {
        'Course': 'course',
        'Task': 'task',
        'Other': 'other',
        'COURSE': 'course',
        'TASK': 'task',
        'OTHER': 'other'
      }
      return typeMap[changeType] || 'other'
    },
    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },
    // 加载更多
    onLoad() {
      const currentFilterData = this.filterData[this.currentFilter]
      if (!currentFilterData.hasMore) {
        currentFilterData.loading = false
        currentFilterData.finished = true
        return
      }
      currentFilterData.page = currentFilterData.page + 1
      this.loadPointsHistory()
    },

    // 显示记录详情
    showRecordDetail(record) {
      Dialog.alert({
        title: '积分详情',
        message: this.getDetailMessage(record),
        confirmButtonText: '确定',
        className: 'points-detail-dialog'
      })
    },

    // 获取详情弹框内容
    getDetailMessage(record) {
      return `
变动类型：${record.changeTypeText}
变动时间：${record.time}
变动积分：${record.points > 0 ? '+' : ''}${record.points}
变动原因：${record.title}
${record.studentName ? `学生姓名：${record.studentName}` : ''}
      `.trim()
    }
  }
}
</script>

<style lang="scss" scoped>
.points-earn-history {
  width: 100%;
  height: 100%;
  background: #f6f8fc;

  .header {
    height: 60px;
    background: white;
    padding: 0 20px;
    border-bottom: 1px solid #eee;

    .nav-bar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 100%;

      .nav-back {
        font-size: 24px;
        color: #333;
        cursor: pointer;
        width: 30px;
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .nav-title {
        font-size: 18px;
        font-weight: bold;
        color: #333;
      }

      .nav-action {
        width: 30px;
      }
    }
  }

  .history-content {
    height: calc(100vh - 60px);
    width: 100%;
    overflow: hidden;
    padding: 15px 0;

    .filter-section {
      margin-bottom: 15px;
      padding: 0 15px;

      .filter-tabs {
        display: flex;
        background: white;
        border-radius: 8px;
        padding: 4px;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

        .filter-tab {
          flex: 1;
          text-align: center;
          padding: 8px 0;
          font-size: 14px;
          color: #666;
          cursor: pointer;
          border-radius: 6px;
          transition: all 0.2s;

          &.active {
            background: #ff6b6b;
            color: white;
            font-weight: 500;
          }
        }
      }
    }

    .history-list {
      height: calc(100% - 50px);
      padding: 0 15px;

      .history-item {
        background: white;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 10px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

        .record-info {
          flex: 1;

          .record-title {
            font-size: 16px;
            color: #333;
            margin-bottom: 5px;
            font-weight: 500;
          }

          .record-details {
            .record-time {
              font-size: 12px;
              color: #999;
              margin-bottom: 3px;
            }

          .record-extra {
            display: flex;
            align-items: center;
            gap: 8px;

            .change-type {
              font-size: 11px;
              color: #666;
              background: #f0f0f0;
              padding: 2px 6px;
              border-radius: 3px;
              max-width: 120px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }

            .student-name {
              font-size: 11px;
              color: #999;
            }
          }
          }
        }

        .record-points {
          font-size: 16px;
          font-weight: bold;
          color: #ff6b6b;

          &.course {
            color: #4ECDC4;
          }

          &.task {
            color: #45B7D1;
          }

          &.other {
            color: #96CEB4;
          }

          &.positive {
            color: #52c41a; // 正数颜色 - 绿色
          }

          &.negative {
            color: #ff4d4f; // 负数颜色 - 红色
          }
        }
      }

      .empty-state {
        text-align: center;
        padding: 60px 20px;

        .empty-icon {
          font-size: 48px;
          margin-bottom: 15px;
        }

        .empty-text {
          font-size: 16px;
          color: #999;
        }
      }
    }
  }
}
</style>

<style lang="scss">
.points-earn-history {
  .van-pull-refresh {
    height: 100%;
  }
  .van-list {
    height: 100%;
    overflow: auto;
    -webkit-overflow-scrolling: touch;
  }
}

// 积分详情弹框样式
.points-detail-dialog {
  .van-dialog {
    border-radius: 12px;
    overflow: hidden;
  }

  .van-dialog__header {
    padding: 20px 20px 15px;
    font-size: 18px;
    font-weight: bold;
    color: #333;
    border-bottom: 1px solid #f0f0f0;
  }

  .van-dialog__message {
    padding: 20px;
    font-size: 14px;
    line-height: 1.6;
    color: #666;
    text-align: left;
    white-space: pre-line;

    // 为积分值添加特殊样式
    .points-value {
      font-weight: bold;
      font-size: 16px;
    }
  }

  .van-dialog__confirm {
    color: #ff6b6b;
    font-weight: 500;
  }
}
</style>
